package com.nebula.salary.portal.controller;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.google.common.base.Strings;
import com.nebula.salary.common.constants.Const;
import com.nebula.salary.common.constants.ReturnMessage;
import com.nebula.salary.common.exception.CustomException;
import com.nebula.salary.common.result.ServerResponse;
import com.nebula.salary.common.utils.SecurityUtil;
import com.nebula.salary.model.dto.BenefitsDto;
import com.nebula.salary.model.dto.PageDto;
import com.nebula.salary.model.pojo.Benefits;
import com.nebula.salary.model.vo.BenefitsEditVo;
import com.nebula.salary.model.vo.PageResult;
import com.nebula.salary.portal.service.IBenefitsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;

/**
 * <p>
 * 节日福利表 前端控制器
 * </p>
 *
 * @author codex
 * @since 2022-01-24
 */
@RestController
@RequestMapping("/benefits")
@Api(tags = "节日福利")
@Transactional(rollbackFor = Exception.class)
public class BenefitsController {
    
    @Resource
    private IBenefitsService benefitsService;
    
    public static final Log log = LogFactory.get();
    
    @ApiOperation(value = "根据节日福利编号获取节日福利信息", notes = "根据节日福利编号获取节日福利信息")
    @GetMapping("/info/{benefitsId}")
    public ServerResponse<BenefitsEditVo> getByBenefitsId(@ApiParam(value = "节日福利编号", required = true)
                                                    @PathVariable Long benefitsId) {
    
        Benefits benefits = benefitsService.getById(benefitsId);
        BenefitsEditVo benefitsEditVo = new BenefitsEditVo();
        BeanUtils.copyProperties(benefits, benefitsEditVo);
        return ServerResponse.createBySuccess(benefitsEditVo);
    }
    
    @ApiOperation(value = "批量删除节日福利", notes = "批量删除节日福利")
    @DeleteMapping("/{benefitsIds}")
    public ServerResponse<String> deleteBenefits(
            @ApiParam(value = "节日福利编号", required = true)
            @PathVariable("benefitsIds") Long[] benefitsIds) {
        try {
            benefitsService.removeByIds(Arrays.asList(benefitsIds));
            return ServerResponse.createBySuccessMessage(ReturnMessage.DELETE_SUCCESS);
        } catch (Exception e) {
            log.error("删除节日福利出现异常，原因：" + e.getMessage());
            return ServerResponse.createByErrorMessage(ReturnMessage.DELETE_ERROR);
        }
    }
    
    @ApiOperation(value = "修改节日福利", notes = "修改节日福利")
    @PutMapping("/")
    public ServerResponse<String> updateBenefits(@RequestBody BenefitsDto benefitsDto) {
        checkData(benefitsDto, Const.TYPE_UPDATE);
        
        try {
            Benefits benefits = new Benefits();
            BeanUtils.copyProperties(benefitsDto, benefits);
            benefits.setIssueYear(benefits.getIssueDate().getYear());
            benefits.setIssueMonth(benefits.getIssueDate().getMonthValue());
            benefitsService.updateById(benefits);
            return ServerResponse.createBySuccessMessage(ReturnMessage.UPDATE_SUCCESS);
        } catch (Exception e) {
            log.error("修改节日福利出现异常，原因：" + e.getMessage());
            return ServerResponse.createByErrorMessage(ReturnMessage.UPDATE_ERROR);
        }
        
    }
    
    @ApiOperation(value = "新增节日福利", notes = "新增节日福利")
    @PostMapping("/")
    public ServerResponse<String> addBenefits(@RequestBody BenefitsDto benefitsDto) {
        checkData(benefitsDto, Const.TYPE_INSERT);
        
        try {
            Benefits benefits = new Benefits();
            BeanUtils.copyProperties(benefitsDto, benefits);
            benefits.setIssueYear(benefits.getIssueDate().getYear());
            benefits.setIssueMonth(benefits.getIssueDate().getMonthValue());
            benefits.setUserId(SecurityUtil.getLoginUser().getUser().getUserId());
            benefitsService.save(benefits);
            return ServerResponse.createBySuccessMessage(ReturnMessage.INSERT_SUCCESS);
        } catch (Exception e) {
            log.error("新增节日福利出现异常，原因：" + e.getMessage());
            return ServerResponse.createByErrorMessage(ReturnMessage.INSERT_ERROR);
        }
    }
    
    @ApiOperation(value = "节日福利", notes = "节日福利")
    @GetMapping("/{year}")
    public ServerResponse<PageResult> benefits(@ApiParam(value = "年份，-1代表所有", required = true)
                                               @PathVariable("year")
                                                       Integer year,
                                               @ApiParam(value = "分页查询数据传输类")
                                                       PageDto pageDto) {
        
        if (year.equals(-1)) {
            return benefitsService.selectAllByPage(pageDto);
        }
        
        return benefitsService.selectBenefitsByPage(year, pageDto);
    }
    
    private void checkData(BenefitsDto benefitsDto, String type) {
        if (benefitsDto == null) {
            throw new CustomException(ReturnMessage.ILLEGAL_REQUEST);
        }
        
        if (Const.TYPE_UPDATE.equals(type)) {
            if (benefitsDto.getBenefitsId() == null) {
                throw new CustomException(ReturnMessage.ILLEGAL_REQUEST);
            }
        }
        
        if (benefitsDto.getBenefitsSalary() == null || benefitsDto.getBenefitsSalary().compareTo(BigDecimal.valueOf(0)) < 0) {
            throw new CustomException("请输入正确的福利金额");
        }
        
        if (benefitsDto.getBenefitsSalary().compareTo(BigDecimal.valueOf(Const.MAX_SALARY)) > 0) {
            throw new CustomException("输入的福利金额超限");
        }
        
        if (benefitsDto.getIssueDate() == null) {
            throw new CustomException("请输入发放日期");
        }
        
        if (Strings.isNullOrEmpty(benefitsDto.getRemark())) {
            throw new CustomException("请输入备注");
        }
        
        if (benefitsDto.getRemark().length() > Const.MAX_REMARK_LENGTH) {
            throw new CustomException("备注长度超限");
        }
    }
    
}

